package com.course.smart_campus.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.course.smart_campus.entity.User;
import com.course.smart_campus.service.UserService;
import com.course.smart_campus.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
* @author feng-shu-sheng
* @description 针对表【user】的数据库操作Service实现
* @createDate 2023-11-07 19:36:31
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Value("${WEIXIN_APP_ID}")
    private String appId;

    @Value("${WEIXIN_APP_SECRET}")
    private String appSecret;
    @Resource
    private UserMapper userMapper;
    @Override
    public Map<String,String> WxLogin(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        String s = HttpUtil.get(url);
        JSONObject sessionInfo = new JSONObject(s);
        System.out.println(sessionInfo);
        if(sessionInfo == null ||sessionInfo.get("errcode")!=null){
            return null;
        }
        String sessionKey = sessionInfo.getStr("session_key");
        String openId = sessionInfo.getStr("openid");
        User user = new User();
        user.setOpenid(openId);
        userMapper.insert(user);
        Map<String,String> map = new java.util.HashMap<>();
        map.put("sessionKey",sessionKey);
        map.put("openId",openId);
        return map;
    }

    @Override
    public boolean upload(String openid, String nickname, String avatarUrl) {
        if(openid!=null && nickname!=null && avatarUrl!=null){
            User user = new User();
            user.setOpenid(openid);
            user.setNickname(nickname);
            user.setAvatar(avatarUrl);
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getOpenid,openid);
            if(userMapper.update(user,wrapper)>0){
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean bind(String openid, String name, Integer id, String classId) {
        if(openid!=null && name!=null && id!=null && classId!=null){
            User user = new User();
            user.setOpenid(openid);
            user.setName(name);
            user.setClassId(classId);
            user.setId(id);
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getOpenid,openid);
            if(userMapper.update(user,wrapper)>0){
                return true;
            }
        }
        return false;
    }
}




